#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'tian'
__data__ = '2021/9/26 11:58'
# software: PyCharm

import uuid
import datetime
from io import BytesIO

from django.shortcuts import render, redirect, reverse, HttpResponse
from django.http import JsonResponse
from django.db.models import Q

from apps.web import models
from apps.web.forms import account
from utils.image_code import check_code


def login(request):
    """
    用户名和密码登录
    :param request:
    :return:
    """
    if request.method == "GET":
        form = account.LoginForm(request)
        return render(request, "login.html", {"form": form})
    form = account.LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password")
        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            pwd=password).first()
        if user_object:
            # 用户名和密码正确，登录成功
            request.session["user_id"] = user_object.pk
            request.session.set_expiry(60 * 60 * 24 * 14)  # 2周
            return redirect('index')
        form.add_error("password", "用户名或密码错误")
    return render(request, "login.html", {"form": form})


def register(request):
    """
    注册
    :param request:
    :return:
    """
    if request.method == "GET":
        form = account.RegFormModel()
        print(form.__dict__)
        return render(request, "register.html", {"form": form})
    form = account.RegFormModel(data=request.POST)
    if form.is_valid():
        instance = form.save()
        policy_object = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=policy_object,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now(),

        )
        return JsonResponse({'status': True, 'data': '/login/'})
    return JsonResponse({"status": False, "error": form.errors})


def login_sms(request):
    """
    短信登录
    :param request:
    :return:
    """
    if request.method == "GET":
        form = account.LoginSmsForm()
        return render(request, "login_sms.html", {"form": form})
    form = account.LoginSmsForm(data=request.POST)
    if form.is_valid():
        user_obj = form.cleaned_data.get("mobile_phone")
        request.session["user_id"] = user_obj.pk
        request.session.set_expiry(60 * 60 * 24 * 14)
        return JsonResponse({"status": True, "data": "/index/"})
    return JsonResponse({"status": False, "error": form.errors})


def send_sms(request):
    """
    发送短信
    :param request:
    :return:
    """
    form = account.SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({"status": True})
    return JsonResponse({"status": False, "error": form.errors})


def image_code(request):
    """
    生成图片验证码
    :param request:
    :return:
    """
    image_object, code = check_code()
    # 图片验证码保存到session中
    request.session['image_code'] = code
    # 定义session的过期时间，默认是两周，这里自定义60秒过期
    request.session.set_expiry(60)
    stream = BytesIO()
    image_object.save(stream, "png")
    return HttpResponse(stream.getvalue())


def logout(request):
    """
    退出,清空session中的值
    :param request:
    :return:
    """
    request.session.flush()
    return redirect("index")

